<script setup lang="ts">
import { importGoodsPrice } from "@/api/basicArchives/goods";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getToken } from "@/utils/auth";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { message } from "@/utils/message";
import AddFill from "@iconify-icons/ep/plus";
import { cloneDeep } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";
import { h, ref, watch } from "vue";
import { useColumns } from "../../utils/columns";
import BatchUpPrice from "./BatchUpPrice.vue";
import ChooseStore from "./ChooseStore.vue";
const { brandColumns } = useColumns();

const props = defineProps({
  brandPriceList: {
    type: Array,
    default: () => []
  }
});

const isInit = ref(false);
const brandList = ref([]);
const storeIds = ref([]);
const childBrandColumns = cloneDeep(brandColumns.slice(1));
delete childBrandColumns[0].cellRenderer;

// ================================ 选择门店
const chooseStoreRef = ref();
const openChooseStore = () => {
  addDialog({
    title: "选择门店",
    props: {
      checkStoreIds: storeIds.value || []
    },
    width: "680px",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(ChooseStore, { ref: chooseStoreRef }),
    beforeSure: done => {
      let storeList = chooseStoreRef.value.getChoseStoreList();
      // 处理回显的数据
      let tempList = cloneDeep(brandList.value);

      // 处理品牌
      let hasBrandIds = tempList.map(v => v.bizId);
      let addBrandList = storeList
        .filter(
          (v, i) =>
            !hasBrandIds.includes(v.brandId) &&
            storeList.findIndex(j => j.brandId == v.brandId) == i
        )
        .map(v => {
          return {
            id: v.brandId,
            bizType: 1,
            bizId: v.brandId,
            brandName: v.brandName,
            goodsStatus: 0,
            discountSalePrice: "",
            discountScore: "",
            score: "",
            storeBuyPrice: "",
            storeSalePrice: "",
            storeList: []
          };
        });
      tempList = tempList.concat(addBrandList);

      // 处理门店
      tempList.forEach(v => {
        let filterList = storeList
          .filter(i => i.brandId == v.bizId)
          .map(i => {
            return {
              bizType: 0, //	业务类型 1品牌 0门店
              bizId: i.id,
              brandName: i.storeName,
              goodsStatus: v.goodsStatus,
              discountSalePrice: v.discountSalePrice,
              discountScore: v.discountScore,
              score: v.score,
              storeBuyPrice: v.storeBuyPrice,
              storeSalePrice: v.storeSalePrice
            };
          });

        if (filterList.length > 0) {
          // 判断原来是否已经存在
          if (v.storeList && v.storeList.length > 0) {
            v.storeList = filterList.map(i => {
              let obj = v.storeList.find(j => j.bizId == i.bizId);
              if (obj) {
                i = obj;
              }
              return i;
            });
          } else {
            v.storeList = filterList;
          }
        } else {
          v.storeList = [];
        }
      });

      brandList.value = tempList;
      storeIds.value = storeList.map(v => v.id);
      done();
    }
  });
};

// ================================ 批量修改价格
const batchUpPriceRef = ref();
const doBatchUpPrice = () => {
  addDialog({
    title: "批量修改",
    props: {
      showStoreIds: storeIds.value || []
    },
    width: "710px",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(BatchUpPrice, { ref: batchUpPriceRef }),
    beforeSure: done => {
      let batchUpData = batchUpPriceRef.value.getBatchUpPriceData();
      if (batchUpData.upStoreList.length == 0) {
        done();
        return;
      }

      // 处理门店的价格
      let brandIds = batchUpData.upStoreList.map(v => v.brandId);
      let storeIds = batchUpData.upStoreList.map(v => v.id);
      let tempList = cloneDeep(brandList.value);
      tempList.forEach(v => {
        // 判断当前品牌下是否需要修改门店价格
        if (brandIds.includes(v.bizId)) {
          v.storeList.forEach(i => {
            if (storeIds.includes(i.bizId)) {
              // 修改价格
              i.storeBuyPrice = batchUpData.storeBuyPrice;
              i.storeSalePrice = batchUpData.storeSalePrice;
              i.score = batchUpData.score;
              i.discountSalePrice = batchUpData.discountSalePrice;
              i.discountScore = batchUpData.discountScore;
            }
          });
        }
      });
      brandList.value = tempList;
      done();
    }
  });
};

const iconHide = ({ row }) => {
  if (!row.storeList || row.storeList.length == 0) {
    return "icon-no";
  }
};

function dealGoodsPriceObj(item) {
  return {
    bizType: item.bizType,
    bizId: item.bizId,
    discountSalePrice: dealDataRide(item.discountSalePrice),
    discountScore: dealDataRide(item.discountScore),
    goodsStatus: item.goodsStatus,
    score: dealDataRide(item.score),
    storeBuyPrice: dealDataRide(item.storeBuyPrice),
    storeSalePrice: dealDataRide(item.storeSalePrice)
  };
}

// 获取显示的品牌价格
const getShowBrandPriceList = () => {
  return brandList.value;
};

// 获取保存的品牌价格
const getSaveBrandPriceList = () => {
  // 校验是否必填
  let goodsSpecBrandRelList = [];
  let isCanNext = true;
  for (let index = 0; index < brandList.value.length; index++) {
    const item = brandList.value[index];

    // 判断品牌
    // if (
    //   !item.storeBuyPrice ||
    //   !item.storeSalePrice ||
    //   !item.score ||
    //   !item.discountSalePrice ||
    //   !item.discountScore
    // ) {
    //   message(
    //     `品牌:'${item.brandName}' 门店进价、零售、积分、折扣售价、折扣积分均不可为空!`,
    //     { type: "warning" }
    //   );
    //   isCanNext = false;
    //   break;
    // }
    goodsSpecBrandRelList.push(dealGoodsPriceObj(item));

    // 判断门店
    if (item.storeList && item.storeList.length > 0) {
      item.storeList.forEach(v => {
        // if (
        //   !v.storeBuyPrice ||
        //   !v.storeSalePrice ||
        //   !v.score ||
        //   !v.discountSalePrice ||
        //   !v.discountScore
        // ) {
        //   message(
        //     `品牌:'${item.brandName}'下的门店('${v.brandName}') 门店进价、零售、积分、折扣售价、折扣积分均不可为空!`,
        //     { type: "warning" }
        //   );
        //   isCanNext = false;
        //   return false;
        // }
        goodsSpecBrandRelList.push(dealGoodsPriceObj(v));
      });
    }
  }

  return { isCanNext, goodsSpecBrandRelList };
};

// 导入数据
const uploadRef = ref();
const handleUpload = option => {
  return new Promise(resolve => {
    const formData = new FormData();
    formData.append("file", option.file);
    importGoodsPrice(formData)
      .then(res => {
        if (res.code == 200) {
          // 解析导入的价格
          let storeProceList = res.data || [];
          storeProceList.forEach(v => {
            v.goodsStatus = 1;
            v.discountSalePrice = dealDataExcept(v.discountSalePrice);
            v.storeBuyPrice = dealDataExcept(v.storeBuyPrice);
            v.storeSalePrice = dealDataExcept(v.storeSalePrice);
            v.score = dealDataExcept(v.score);
            v.discountScore = dealDataExcept(v.discountScore);
            v.brandId = v.expandBrandId;
            v.expandBrandName = v.expandBrandName; // 品牌名称
            v.brandName = v.bizName; // 默认赋值 商品名称
          });

          // 处理品牌
          let hasBrandIds = brandList.value.map(v => v.bizId);
          let addBrandList = storeProceList
            .filter(
              (v, i) =>
                !hasBrandIds.includes(v.brandId) &&
                storeProceList.findIndex(j => j.brandId == v.brandId) == i
            )
            .map(v => {
              return {
                id: v.brandId,
                bizType: 1,
                bizId: v.brandId,
                brandName: v.expandBrandName,
                goodsStatus: 0,
                discountSalePrice: "",
                discountScore: "",
                score: "",
                storeBuyPrice: "",
                storeSalePrice: "",
                storeList: []
              };
            });
          brandList.value = brandList.value.concat(addBrandList);

          // 处理门店
          let tempStoreIds = [];
          brandList.value.forEach(v => {
            let filterList = storeProceList.filter(i => i.brandId == v.bizId);
            if (filterList.length > 0) {
              // 判断原来是否已经存在,存在替换价格
              if (v.storeList && v.storeList.length > 0) {
                let hasStoreIds = [];
                v.storeList.forEach(s => {
                  hasStoreIds.push(s.bizId);
                  let obj = filterList.find(i => i.bizId == s.bizId);
                  if (obj) {
                    s.discountSalePrice = obj.discountSalePrice;
                    s.storeBuyPrice = obj.storeBuyPrice;
                    s.storeSalePrice = obj.storeSalePrice;
                    s.score = obj.score;
                    s.discountScore = obj.discountScore;
                  }
                });
                let addStoreList = filterList.filter(
                  i => !hasStoreIds.includes(i.bizId)
                );
                if (addStoreList.length > 0) {
                  v.storeList = v.storeList.concat(addStoreList);
                }
              } else {
                v.storeList = filterList;
              }
            }
            tempStoreIds = tempStoreIds.concat(v.storeList.map(i => i.bizId));
          });
          storeIds.value = tempStoreIds;
          message("导入成功", { type: "success" });
        }
      })
      .catch(e => {
        let tips = e || "导入异常";
        if (e && e.split(";").length > 0) {
          tips = e.split(";").join("<br />");
        }
        ElMessageBox.alert(tips, "温馨提示", {
          dangerouslyUseHTMLString: true,
          showClose: true,
          confirmButtonText: "确认"
        });
        // message("导入异常", { type: "error" });
      })
      .finally(() => {
        uploadRef.value.clearFiles();
      });
    resolve(true);
  });
};

const downTemp = () => {
  window.open("/template/导入价格模版.xls", "_blank");
};

const beforeUpload = file => {
  const last = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension1 = last == "xls";
  const extension2 = last == "xlsx";
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!extension1 && !extension2) {
    message("上传文件格式只能是xls、xlsx格式!", { type: "warning" });
    return false;
  }
  if (!isLt10M) {
    message("文件大小不能超过 10MB!", { type: "warning" });
    return false;
  }
};

watch(
  () => props.brandPriceList,
  newValue => {
    if (newValue.length > 0 && !isInit.value) {
      isInit.value = true;
      brandList.value = newValue;

      // 获取门店id
      let tempStoreIds = [];
      brandList.value.forEach(v => {
        if (v.storeList) {
          tempStoreIds = tempStoreIds.concat(v.storeList.map(i => i.bizId));
        }
      });
      storeIds.value = tempStoreIds;
    }
  },
  { immediate: true }
);

defineExpose({ getShowBrandPriceList, getSaveBrandPriceList });
</script>

<template>
  <div class="w-full mb-[20px]">
    <div class="mb-[10px] flex justify-between">
      <el-button
        :icon="useRenderIcon(AddFill)"
        type="primary"
        plain
        @click="openChooseStore"
        >特殊门店</el-button
      >
      <div class="flex">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="品牌下没有需要设置价格的门店~"
          :disabled="storeIds.length > 1"
          placement="top-start"
        >
          <el-button
            type="primary"
            :disabled="storeIds.length === 0"
            class="mr-[10px]"
            @click="doBatchUpPrice"
            >批量修改</el-button
          >
        </el-tooltip>
        <el-upload
          ref="uploadRef"
          :headers="{ accessToken: getToken() }"
          :http-request="handleUpload"
          :before-upload="beforeUpload"
          accept=".xls, .xlsx"
          action="no"
          class="mr-[10px]"
          :show-file-list="false"
          :limit="1"
        >
          <el-button type="primary">导入价格</el-button>
        </el-upload>
        <el-button @click="downTemp">导出模版</el-button>
      </div>
    </div>
    <pure-table
      row-key="id"
      align-whole="center"
      :header-cell-style="{
        background: 'var(--el-fill-color-light)',
        color: 'var(--el-text-color-primary)'
      }"
      max-height="500"
      :row-class-name="iconHide"
      :data="brandList"
      :columns="brandColumns"
    >
      <template #expand="{ row }">
        <div class="ml-[52px]">
          <pure-table
            :data="row.storeList"
            align-whole="center"
            class="bd-hide"
            :show-header="false"
            :columns="childBrandColumns"
          />
        </div>
      </template>
    </pure-table>
  </div>
</template>
<style lang="scss" scoped>
:deep(.bd-hide .el-table--fit .el-table__inner-wrapper:before) {
  background-color: #fff;
}
:deep(.icon-no .el-table__expand-icon) {
  display: none;
}
</style>
